using FluentValidation;
using Zhaoxi.Zhihu.SharedKerel.Messaging;
using Zhaoxi.Zhihu.SharedKerel.Paging;
using Zhaoxi.Zhihu.SharedKerel.Result;
using Zhaoxi.Zhihu.UseCases.Common.Attributes;
using Zhaoxi.Zhihu.UseCases.Common.Queries.Interfaces;

namespace Zhaoxi.Zhihu.UseCases.Answers.Command;

[Authorize]
public record GetAnswerjsQuery(int QuestionId, Pagination Pagination) :
    IQuery<Result<PagedList<AnswerDto>>>;

public class GetAnswerjsQueryValidator : AbstractValidator<GetAnswerjsQuery>
{
    public GetAnswerjsQueryValidator()
    {
        RuleFor(command=> command. QuestionId)
            .GreaterThan(0);
    }
       
}

public class GetAnswersQueryHandler(IDaraQueryService dataQueryService) :
    IQueryHandler<GetAnswerjsQuery, Result<PagedList<AnswerDto>>>
{
   

    public async Task<Result<PagedList<AnswerDto>>> Handle(GetAnswerjsQuery request, CancellationToken cancellationToken)
    {
        var queryable = from answer in dataQueryService.Answers
            join user in dataQueryService.AppUsers on answer.CreatedBy equals user.Id
            where answer.QuestionId == request.QuestionId
            orderby answer.LikeCount descending
            select new AnswerDto
            {
                Id = answer.Id,
                Content = answer.Content,
                LikeCount = answer.LikeCount,
                LastModifiedAt = answer.LastModifiedAt,
                CreatedBy = answer.CreatedBy,
                CreatedByNickName = user.Nickname,
                CreatedByBio = user.Bio
            };
        var answers = await dataQueryService.PageListAsync(queryable, request.Pagination);
        return answers. Count == 0 ? Result.NotFound("回答不存在") : Result. Success(answers);
    }
}